// static/js/main.js

// 全局变量来跟踪初始化状态
let isInitialized = false;

console.log('开始加载 main.js');

// 首页功能
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化...');
    
    if (isInitialized) {
        console.log('已经初始化，跳过');
        return;
    }
    isInitialized = true;
    // 分页配置
    const paginationConfig = {
        storiesPerPage: 6, // 每页显示的故事数量
        currentPage: 1,
        totalPages: 1,
        currentCategory: 'all'
    };
    
    // 获取所有故事卡片
    const storyCards = Array.from(document.querySelectorAll('.stories-container .story-card'));
    
    // 保持原有的分类标签切换功能
    const tabs = document.querySelectorAll('.tab');
    
    if (tabs.length > 0) {
        tabs.forEach(tab => {
            tab.addEventListener('click', function(e) {
                e.preventDefault();
                
                // 移除所有标签的活动状态
                tabs.forEach(t => t.classList.remove('active'));
                
                // 为当前点击的标签添加活动状态
                this.classList.add('active');
                
                // 获取选择的分类
                const category = this.getAttribute('data-category');
                paginationConfig.currentCategory = category;
                
                // 重置到第一页
                paginationConfig.currentPage = 1;
                
                // 更新分页和显示
                updatePagination();
                displayStories();
            });
        });
    }
    
    // 根据分类过滤故事
    function filterStoriesByCategory(category) {
        return storyCards.filter(card => {
            if (category === 'all') {
                return true;
            }
            return card.getAttribute('data-category') === category;
        });
    }
    
    // 显示当前页的故事
    function displayStories() {
        // 获取当前分类下的所有故事
        const filteredStories = filterStoriesByCategory(paginationConfig.currentCategory);
        
        // 隐藏所有故事
        storyCards.forEach(card => {
            card.style.display = 'none';
        });
        
        // 计算当前页应该显示的故事范围
        const startIndex = (paginationConfig.currentPage - 1) * paginationConfig.storiesPerPage;
        const endIndex = startIndex + paginationConfig.storiesPerPage;
        
        // 显示当前页的故事
        const storiesToShow = filteredStories.slice(startIndex, endIndex);
        storiesToShow.forEach(card => {
            card.style.display = 'block';
        });
    }
    
    // 计算总页数
    function calculateTotalPages() {
        const filteredStories = filterStoriesByCategory(paginationConfig.currentCategory);
        return Math.ceil(filteredStories.length / paginationConfig.storiesPerPage) || 1;
    }
    
    // 更新分页器显示
    function updatePagination() {
        // 重新计算总页数
        paginationConfig.totalPages = calculateTotalPages();
        
        // 确保当前页不超过总页数
        if (paginationConfig.currentPage > paginationConfig.totalPages) {
            paginationConfig.currentPage = paginationConfig.totalPages;
        }
        
        // 如果当前页小于1，则设为1
        if (paginationConfig.currentPage < 1) {
            paginationConfig.currentPage = 1;
        }
        
        // 更新页码信息
        const currentPageEl = document.getElementById('current-page');
        const totalPagesEl = document.getElementById('total-pages');
        if (currentPageEl) currentPageEl.textContent = paginationConfig.currentPage;
        if (totalPagesEl) totalPagesEl.textContent = paginationConfig.totalPages;
        
        // 更新上一页和下一页按钮状态
        const prevPageItem = document.getElementById('prev-page');
        const nextPageItem = document.getElementById('next-page');
        
        // 上一页按钮状态
        if (prevPageItem) {
            if (paginationConfig.currentPage === 1) {
                prevPageItem.classList.add('disabled');
            } else {
                prevPageItem.classList.remove('disabled');
            }
        }
        
        // 下一页按钮状态
        if (nextPageItem) {
            if (paginationConfig.currentPage === paginationConfig.totalPages) {
                nextPageItem.classList.add('disabled');
            } else {
                nextPageItem.classList.remove('disabled');
            }
        }
        
        // 更新页码按钮
        updatePageNumbers();
    }
    
    // 更新页码按钮
    function updatePageNumbers() {
        const paginationUl = document.getElementById('story-pagination');
        if (!paginationUl) return;
        
        // 清除除上一页和下一页外的所有页码按钮
        const pageItems = paginationUl.querySelectorAll('.page-item:not(#prev-page):not(#next-page)');
        pageItems.forEach(item => item.remove());
        
        // 生成新的页码按钮
        const nextPageItem = document.getElementById('next-page');
        if (!nextPageItem) return;
        
        for (let i = 1; i <= paginationConfig.totalPages; i++) {
            const pageItem = document.createElement('li');
            pageItem.className = 'page-item';
            if (i === paginationConfig.currentPage) {
                pageItem.classList.add('active');
            }
            
            const pageLink = document.createElement('a');
            pageLink.className = 'page-link';
            pageLink.href = '#';
            pageLink.textContent = i;
            pageLink.addEventListener('click', function(e) {
                e.preventDefault();
                paginationConfig.currentPage = i;
                updatePagination();
                displayStories();
            });
            
            pageItem.appendChild(pageLink);
            paginationUl.insertBefore(pageItem, nextPageItem);
        }
    }
    
    // 分页器点击事件
    const paginationEl = document.getElementById('story-pagination');
    if (paginationEl) {
        paginationEl.addEventListener('click', function(e) {
            e.preventDefault();
            
            const target = e.target;
            const parentItem = target.parentElement;
            
            // 忽略禁用的按钮和非链接元素
            if (parentItem.classList.contains('disabled') || target.tagName !== 'A') {
                return;
            }
            
            // 上一页
            if (parentItem.id === 'prev-page') {
                if (paginationConfig.currentPage > 1) {
                    paginationConfig.currentPage--;
                    updatePagination();
                    displayStories();
                }
                return;
            }
            
            // 下一页
            if (parentItem.id === 'next-page') {
                if (paginationConfig.currentPage < paginationConfig.totalPages) {
                    paginationConfig.currentPage++;
                    updatePagination();
                    displayStories();
                }
                return;
            }
        });
    }
    
    // 搜索功能
    const searchForm = document.getElementById('searchForm');
    if (searchForm) {
        searchForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            
            // 过滤故事卡片
            storyCards.forEach(card => {
                const title = card.querySelector('h3').textContent.toLowerCase();
                const excerpt = card.querySelector('.story-excerpt').textContent.toLowerCase();
                const author = card.querySelector('.author') ? card.querySelector('.author').textContent.toLowerCase() : '';
                
                const matchesSearch = 
                    title.includes(searchTerm) || 
                    excerpt.includes(searchTerm) || 
                    author.includes(searchTerm);
                
                // 如果匹配搜索词，则移除隐藏类；否则添加隐藏类
                if (matchesSearch) {
                    card.classList.remove('search-hidden');
                } else {
                    card.classList.add('search-hidden');
                }
            });
            
            // 重置到第一页并更新显示
            paginationConfig.currentPage = 1;
            updatePagination();
            displayStories();
        });
        
        // 添加搜索隐藏类的样式处理
        const style = document.createElement('style');
        style.textContent = '.search-hidden { display: none !important; }';
        document.head.appendChild(style);
    }
    
    // 登录表单处理
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        console.log('登录表单找到');
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            console.log('登录表单提交');
            
            const messageEl = document.getElementById('login-message');
            const identifier = document.getElementById('identifier').value;
            const password = document.getElementById('password').value;
            
            // 简单的前端验证
            if (!identifier || !password) {
                showMessage(messageEl, '请填写所有字段', 'error');
                return;
            }
            
            // 显示加载状态
            const submitButton = loginForm.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.textContent = '登录中...';
            submitButton.disabled = true;
            
            // 收集表单数据
            const formData = new FormData(loginForm);
            
            // 发送登录请求
            fetch('/user/login/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCSRFToken()
                }
            })
            .then(response => response.json())
            .then(data => {
                console.log('登录响应:', data);
                if (data.success) {
                    showMessage(messageEl, data.message, 'success');
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1000);
                } else {
                    showMessage(messageEl, data.message, 'error');
                }
            })
            .catch(error => {
                console.error('登录错误:', error);
                showMessage(messageEl, '登录过程中发生错误，请稍后重试', 'error');
            })
            .finally(() => {
                // 恢复按钮状态
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            });
        });
    } else {
        console.log('未找到登录表单');
    }
    
    // 注册表单处理
    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        console.log('注册表单找到');
        registerForm.addEventListener('submit', function(e) {
            e.preventDefault();
            console.log('注册表单提交');
            
            const messageEl = document.getElementById('register-message');
            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;
            const nickname = document.getElementById('nickname').value;
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            // 前端验证 - 用户名和邮箱至少填写一个
            if ((!username && !email) || !password || !confirmPassword) {
                showMessage(messageEl, '用户名和邮箱至少填写一个，密码必填', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage(messageEl, '密码和确认密码不匹配', 'error');
                return;
            }
            
            if (password.length < 1) {
                showMessage(messageEl, '密码不能为空', 'error');
                return;
            }
            
            // 显示加载状态
            const submitButton = registerForm.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.textContent = '注册中...';
            submitButton.disabled = true;
            
            // 收集表单数据
            const formData = new FormData(registerForm);
            
            // 发送注册请求
            fetch('/user/register/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCSRFToken()
                }
            })
            .then(response => response.json())
            .then(data => {
                console.log('注册响应:', data);
                if (data.success) {
                    showMessage(messageEl, data.message, 'success');
                    setTimeout(() => {
                        window.location.href = '/user/login/';
                    }, 1000);
                } else {
                    showMessage(messageEl, data.message, 'error');
                }
            })
            .catch(error => {
                console.error('注册错误:', error);
                showMessage(messageEl, '注册过程中发生错误，请稍后重试', 'error');
            })
            .finally(() => {
                // 恢复按钮状态
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            });
        });
    } else {
        console.log('未找到注册表单');
    }
    
    // 故事生成表单处理
    const storyForm = document.getElementById('storyForm');
    if (storyForm) {
        storyForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 显示加载状态
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').style.display = 'none';
            
            // 收集表单数据
            const formData = new FormData(storyForm);
            
            // 发送生成故事请求
            fetch('/generate/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示结果
                    document.getElementById('storyTitle').textContent = data.title;
                    document.getElementById('storyContent').textContent = data.content;
                    document.getElementById('result').style.display = 'block';
                } else {
                    alert('生成故事失败: ' + data.message);
                }
            })
            .catch(error => {
                alert('生成故事过程中发生错误，请稍后重试');
                console.error('Error:', error);
            })
            .finally(() => {
                // 隐藏加载状态
                document.getElementById('loading').style.display = 'none';
            });
        });
    }
    
    // 个人中心表单处理
    const profileForm = document.getElementById('profileForm');
    if (profileForm) {
        // 头像预览功能
        const headImgInput = document.getElementById('head_img');
        const avatarPreview = document.getElementById('avatarPreview');
        
        if (headImgInput && avatarPreview) {
            headImgInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        avatarPreview.src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
        
        profileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const messageEl = document.getElementById('profile-message');
            const username = document.getElementById('username').value.trim();
            const email = document.getElementById('email').value.trim();
            
            // 前端验证 - 用户名和邮箱至少填写一个
            if (!username && !email) {
                showMessage(messageEl, '用户名和邮箱至少填写一个', 'error');
                return;
            }
            
            // 显示加载状态
            const submitButton = profileForm.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.textContent = '保存中...';
            submitButton.disabled = true;
            
            // 收集表单数据
            const formData = new FormData(profileForm);
            
            // 发送更新请求
            fetch('/user/profile/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(messageEl, data.message, 'success');
                    // 刷新页面以更新显示的信息
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    showMessage(messageEl, data.message, 'error');
                }
            })
            .catch(error => {
                showMessage(messageEl, '更新过程中发生错误，请稍后重试', 'error');
                console.error('Error:', error);
            })
            .finally(() => {
                // 恢复按钮状态
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            });
        });
    }
    
    // 修改密码表单处理
    const changePasswordForm = document.getElementById('changePasswordForm');
    if (changePasswordForm) {
        changePasswordForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const messageEl = document.getElementById('password-message');
            const oldPassword = document.getElementById('old_password').value;
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            // 前端验证
            if (!oldPassword || !newPassword || !confirmPassword) {
                showMessage(messageEl, '请填写所有字段', 'error');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                showMessage(messageEl, '新密码和确认密码不匹配', 'error');
                return;
            }
            
            if (newPassword.length < 1) {
                showMessage(messageEl, '新密码不能为空', 'error');
                return;
            }
            
            // 显示加载状态
            const submitButton = changePasswordForm.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.textContent = '修改中...';
            submitButton.disabled = true;
            
            // 收集表单数据
            const formData = new FormData(changePasswordForm);
            
            // 发送修改密码请求
            fetch('/user/change-password/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(messageEl, data.message, 'success');
                    // 清空表单
                    changePasswordForm.reset();
                    // 2秒后跳转到个人中心
                    setTimeout(() => {
                        window.location.href = '/user/profile/';
                    }, 2000);
                } else {
                    showMessage(messageEl, data.message, 'error');
                }
            })
            .catch(error => {
                showMessage(messageEl, '修改密码过程中发生错误，请稍后重试', 'error');
                console.error('Error:', error);
            })
            .finally(() => {
                // 恢复按钮状态
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            });
        });
    }
    
    // 初始化分页器和显示
    if (document.getElementById('story-pagination')) {
        updatePagination();
        displayStories();
    } else {
        console.log('没有找到分页器，跳过初始化');
    }
});

// 显示消息函数
function showMessage(element, message, type) {
    element.textContent = message;
    element.className = 'message ' + type;
    element.style.display = 'block';
    
    // 3秒后自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            element.style.display = 'none';
        }, 3000);
    }
}

// 获取CSRF token的函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 获取CSRF token的替代方法
function getCSRFToken() {
    // 从表单中获取CSRF token
    const csrfInput = document.querySelector('input[name="csrfmiddlewaretoken"]');
    if (csrfInput) {
        return csrfInput.value;
    }
    // 从 cookie中获取
    return getCookie('csrftoken');
}